package com.banmao.youZone.util;

import cn.hutool.extra.spring.SpringUtil;
import com.banmao.youZone.consts.CommonConst;
import com.banmao.youZone.entity.UserVO;
import com.banmao.youZone.mapper.UserMapper;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;
import java.util.Optional;

@Slf4j
public class RequestUtil {

    private RequestUtil() {}

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest();
    }

    public static HttpServletResponse getResponse() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getResponse();
    }

    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    public static UserVO getSessionUserPure() {
        UserMapper userMapper = SpringUtil.getBean(UserMapper.class);

        Object userobj = getSession().getAttribute(CommonConst.USER_SESSION);
        if (userobj instanceof UserVO userVO) {
            userVO = userMapper.selectById(userVO.getUserId());
            getSession().setAttribute(CommonConst.USER_SESSION, userVO);
            return userVO;
        }

        Cookie userIdCookie = Arrays.stream(Optional.ofNullable(getRequest().getCookies())
                        .orElse(new Cookie[]{}))
                .filter(c -> CommonConst.USER_SESSION.equals(c.getName()))
                .findFirst()
                .orElse(null);
        if (userIdCookie != null && userIdCookie.getValue() != null) {
            String userIdStr = userIdCookie.getValue();
            UserVO userVO = userMapper.selectById(userIdStr);
            if (userVO != null) {
                getSession().setAttribute(CommonConst.USER_SESSION, userVO);
                return userVO;
            }
        }
        return null;
    }

    public static UserVO getSessionUser() {

        UserVO sessionUserPure = getSessionUserPure();
        if (sessionUserPure != null) {
            return sessionUserPure;
        }

        try {
            getResponse().sendRedirect("/");
        } catch (Exception e) {
            log.error("[RequestUtil]重定向异常,msg:{},error:", e.getMessage(), e);
        }
        throw new IllegalArgumentException("未选择用户");

    }

}
